﻿using BootstrapBlazor.Components;
using GMS.NET.Dto.System.AccRoles.Output;
using GMS.NET.Dto.System.Layout.Ouput;
using System.Reflection;

namespace GMS.NET.Web.Components.Shared.Global.Misc
{
    public static class Utilitys
    {
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="queryPivot"></param>
        /// <param name="pageOptions"></param>
        /// <returns></returns>
        public static async Task<(bool IsSearch,bool IsOrder)> GetSearchAsync<T>(this QueryPivot queryPivot, QueryPageOptions pageOptions) where T : class
        {
            bool IsSearch = false;
            bool IsOrder = false;
            try
            {
                queryPivot.PageIndex = pageOptions.PageIndex;
                queryPivot.PageSize = pageOptions.PageItems;
                if(pageOptions.SortName is not null)
                {
                    IsOrder = true;
                    queryPivot.PageSort = $"{pageOptions.SortName} {pageOptions.SortOrder}";
                }
                queryPivot.IsPage = pageOptions.IsPage;
                if (pageOptions.CustomerSearches.Any())
                {
                    await Task.Run(() =>
                    {
                        var whereModel = new List<WhereModel>();
                        var TModel = pageOptions.SearchModel as T;
                        PropertyInfo[] PropertyInfos = TModel!.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
                        foreach (var PropertyInfo in PropertyInfos)
                        {
                            var Attr = PropertyInfo.GetCustomAttribute<QueryPivotAttribute>();
                            var Name = !string.IsNullOrWhiteSpace(Attr!.FieldName) ? Attr.FieldName : PropertyInfo.Name;
                            var Value = PropertyInfo.GetValue(TModel, null);
                            if (Attr is not null && Value is not null)
                            {
                                whereModel.Add(new WhereModel
                                {
                                    FieldName = Name,
                                    FieldValue = Value,
                                    ConditionalType = Attr.ConditionalType,
                                    CSharpTypeName = Attr.CSharpTypeName,
                                });
                            }
                        }
                        queryPivot.WhereModel = whereModel;
                        IsSearch= true;
                    });
                }
            }
            catch (Exception)
            {
                IsSearch= false;
                IsOrder=false;
            }
            return (IsSearch,IsOrder);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static async Task<MenuItem> RecursiveCopyAsync(this MenuItemSync source)
        {
            if (source == null)
                return null!;

            MenuItem target = new MenuItem
            {
                Text = source.Text,
                Icon = source.Icon,
                Url = source.Url,
                CssClass = source.CssClass,
                IsActive = false
            };

            List<MenuItem> targetItems = new List<MenuItem>();

            if (source.Items is not null)
                foreach (var child in source.Items!)
                {
                    targetItems.Add(await RecursiveCopyAsync(child));
                }

            target.Items = targetItems;

            return target;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static async Task<TreeViewItem<WaitRess>> RecursiveCopyAsync(this WaitRess source)
        {
            if (source == null)
                return null!;

            TreeViewItem<WaitRess> target = new (source)
            {
                HasChildren= source.HasChildren,
                CheckedState=source.IsChecked?CheckboxState.Checked:CheckboxState.UnChecked,
                Icon = source.Icon,
                Text = source.Text,
                IsDisabled= source.IsDisabled,
            };

            List<TreeViewItem<WaitRess>> targetItems = new List<TreeViewItem<WaitRess>>();

            if (source.Children is not null)
                foreach (var child in source.Children!)
                {
                    targetItems.Add(await RecursiveCopyAsync(child));
                }

            target.Items = targetItems;

            return target;
        }
    }
    public class TreeConverter
    {
        public static List<WaitRess> ConvertToTree(List<WaitRess> flatList)
        {
            var rootNodes = GetRootNodes(flatList);
            foreach (var rootNode in rootNodes)
            {
                AddChildren(rootNode, flatList);
            }
            return rootNodes;
        }

        private static List<WaitRess> GetRootNodes(List<WaitRess> flatList)
        {
            return flatList.Where(x => x.ParentId ==Guid.Parse(DataConst.TopParentGuid)).ToList();
        }

        private static void AddChildren(WaitRess node, List<WaitRess> flatList)
        {
            var children = flatList.Where(x => x.ParentId == node.Id).ToList();
            foreach (var child in children)
            {
                AddChildren(child, flatList);
            }
            node.HasChildren = children.Any();
            node.Children!.AddRange(children);
        }
    }
}
